<script setup>
import _ from 'lodash';
import {computed, onMounted, reactive, toRefs, watch} from "vue";
import {api} from "@jzl/api";
import {DFT_ICONS} from "@jzl/icons";

defineOptions({
  name: 'BuilderCompsCloud'
});

const emit = defineEmits(['create-page-comp']);
const props = defineProps({
  queryPageType: {
    type: [ Number, String ],
    default: ''
  },
  show: {
    type: Boolean,
    default: false
  },
})

const {
  pageType,
  className,
  pinMenu,
  pinProp,
  appId,
  queryText,
  loading,
  finished,
  elemsCloud,
  pagination,
  libs,
  tags,
  compLib,
  compTag
} = toRefs(reactive({
  pageType: 2,
  className: "page-builder-h5",
  pinMenu: true,
  pinProp: true,

  // appCate: null,
  appId: -200,
  queryText: '',
  loading: false,
  finished: false,
  elemsCloud: [],
  pagination: {
    page: 1,
    pageSize: 50,
    total: 0
  },
  libs: [],
  tags: [],
  compLib: '',
  compTag: ''
}))

const libTotal = computed(() => {
  return _.sumBy(libs.value, t => Number(t.count) || 0);
})

const compTotal = computed(() => {
  return _.sumBy(tags.value, t => Number(t.count) || 0);
})

const _loadCloudComps = $utils.buffer(async (isFirst = false) => {
  // let queryAppId = _.get(this.appCate, "group_id");
  if (isFirst) {
    pagination.value.page = 1;
    pagination.value.total = 0;
  } else if (loading.value) {
    return;
  }

  loading.value = true;
  let query = getQueryParam();
  let ret = await api.comp.getCompList(query, pagination.value);
  let total = _.get(ret, 'count', 0);

  elemsCloud.value = ret?.rows || [];
  pagination.value.total = total;
  loading.value = false;

  checkFinish();
});

const getQueryParam = () => {
  let app_id = -1;
  let cate = -1;

  if (appId.value === -200) {
    cate = -1;
  } else if (appId.value === -100) {
    // project_id = -1;
    cate = 1;
  } else if (appId.value === -1) {
    // project_id = this.app.project_id;
    cate = 2;
  } else {
    cate = 3;
    app_id = appId.value;
  }

  return {cate, app_id, comp_lib: compLib.value, tag: compTag.value};
}

const loadLibs = async () => {
  let query = getQueryParam();
  let ret = await api.comp.getCompLibs(query);

  libs.value = ret;
}

const loadTags = async () => {
  let query = getQueryParam();
  let iTags = await api.comp.getCompTags(query);
  tags.value = iTags;
}

const loadCloudComps = async (isFirst = false) => {
  await _loadCloudComps(isFirst);
}

const checkFinish = () => {
  finished.value = pagination.value.total <= (pagination.value.pageSize * pagination.value.page);
}

const handleCompPreview = (comp) => {

}

const handleCompSelect = (comp) => {
  emit("create-page-comp", _.cloneDeep(comp));
}

const handleSelectLib = (lib) => {
  let cLib = lib?.comp_lib || "";

  if (compLib.value === cLib) {
    compLib.value = "";
  } else {
    compLib.value = cLib;
  }
}

const handleSelectTag = (tag) => {
  let iTag = tag?.tag || "";

  if (compTag.value === iTag) {
    compTag.value = "";
  } else {
    compTag.value = iTag;
  }
}

onMounted(() => {
  loadLibs();
  loadTags();
  loadCloudComps(true);
})

watch(() => appId.value, () => {
  compLib.value = '';
  compTag.value = "";
  loadLibs();
  loadTags();
  loadCloudComps(true);
})

watch(() => compLib.value, () => {
  compTag.value = "";
  loadTags();
  loadCloudComps(true);
})

watch(() => compTag.value, () => {
  loadCloudComps(true);
})
</script>

<template>
  <div
    class="form-list-wrap comp-cloud-win"
    :class="{
      'page-select-h5': queryPageType == 2,
      'page-select-pc': queryPageType == 5,
      'page-select-bs': queryPageType == 1
    }">
    <AppCate
      v-model="appId"
      class="w-[140px] h-auto min-w-1"
    />
    <div class="comp-cloud-tags-wrap" v-if="libs && libs.length">
      <div class="comp-cloud-tags-container">
        <div class="comp-cloud-tags-title">Libs</div>
        <el-scrollbar
          class="comp-cloud-tags"
        >
          <el-button
            size="mini"
            @click="handleSelectLib('')"
            :type="'' === compLib ? 'primary': 'text'"
          >全部（{{ libTotal }}）
          </el-button>
          <el-button
            v-for="lib in libs"
            size="mini"
            @click="handleSelectLib(lib)"
            :type="lib.comp_lib === compLib ? 'primary': 'text'"
          >{{ lib.comp_lib }}（{{ lib.count }}）
          </el-button>
        </el-scrollbar>
      </div>

      <div
        class="comp-cloud-tags-container"
        v-if="tags?.length">
        <div class="comp-cloud-tags-title">Tags</div>
        <el-scrollbar
          class="comp-cloud-tags"
        >
          <el-button
            size="mini"
            @click="handleSelectTag('')"
            :type="'' === compTag ? 'primary': 'text'"
          >全部（{{ compTotal }}）
          </el-button>
          <el-button
            v-for="tag in tags"
            size="mini"
            @click="handleSelectTag(tag)"
            :type="tag.tag === compTag ? 'primary': 'text'"
          >{{ tag.tag }}（{{ tag.count }}）
          </el-button>
        </el-scrollbar>
      </div>
    </div>

    <div class="page-cloud-comps-wrap">
      <van-list
        :finished="finished"
        finished-text="没有更多了"
        @load="loadCloudComps"
        class="page-cloud-comps-container"
      >
        <div
          class="page-cloud-comps"
          v-jloading="loading"
        >
          <template
            v-for="comp in elemsCloud"
            :key="comp.component"
          >
            <div
              class="page-card pl-1 pr-1"
              unselectable="on"
              v-resp="{ type: 'c24', container: 'parent', smc: 8, mdc: 6, lgc: 4, xlc: 2 }">
              <PageThumb
                :img="comp?.thumb"
                ratio-height="70%"
                mode="comp"
              >
                <div
                  class="page-code bottom-[40px]"
                  v-text="comp.comp_lib"
                  v-copy="comp.comp_lib"
                  v-tippy="{ arrow: true, placement : 'left' }"
                  content="点击复制"
                />
                <div
                  class="page-code"
                  v-text="comp.comp_name"
                  v-copy="comp.comp_name"
                  v-tippy="{ arrow: true, placement : 'left' }"
                  content="点击复制"
                />
                <!--<i class="page-card-action fa fa-eye preview" v-tippy="{ arrow: true, placement : 'left' }" content="预览"
                   @click="handleCompPreview(comp)"></i>-->
                <JIcon
                  class="page-card-action"
                  :icon="DFT_ICONS.add"
                  v-tippy="{ arrow: true, placement : 'left' }"
                  content="添加"
                  @click="handleCompSelect(comp)"
                />
              </PageThumb>
              <div class="page-info">
                <div
                  class="art-font page-title"
                  v-text="comp.name"
                />
              </div>
            </div>
          </template>
        </div>
      </van-list>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.comp-cloud-win {
  /*height: 450px;*/

  .page-cloud-comps-wrap {
    flex: 1;
  }

  .page-cloud-comps-container {
    height: 100%;
    overflow-y: auto;
  }

  .page-cloud-comps {
    display: flex;
    flex-wrap: wrap;
    min-height: 330px;

    .page-card {
      /*width: 192px;
      height: 120px;*/
      width: auto;
      height: auto;
    }
  }
}

.comp-cloud-tags-wrap {
  width: 120px;
  padding: 5px;
  height: 100%;
  border-right: 1px solid #F1F5F9;
  display: flex;
  flex-flow: column;
}

.comp-cloud-tags-container {
  flex: 1;
  transition: all .2s;
  overflow: hidden;
  border-bottom: 1px solid #F1F5F9;

  &:hover {
    flex: 2;
  }

  &:last-child {
    border-bottom: none;
  }
}

.comp-cloud-tags-title {
  padding: 5px 0;
  font-size: 13px;
  color: #555;
  font-weight: bold;
}

.comp-cloud-tags {
  height: 100%;
  flex: 1;

  .el-button {
    display: block;
    margin: 0px;
    padding-left: 5px;
    padding-right: 0px;
  }
}
</style>
